<?php
/**
 * Created by PhpStorm.
 * User: long
 * Date: 2016/7/19
 * Time: 15:45
 */

namespace System\Controller;


use Common\Controller\AdminbaseController;
use System\Model\RequestRecordModel;


class RequestRecordController extends AdminbaseController
{
    protected $request_record_model;

    public function __construct()
    {
        parent::__construct();
        $this->request_record_model = new RequestRecordModel();
    }

    public function lists()
    {
        $this->_list();
        $this->display();
    }

    private function _list()
    {
        $fields = [
            'start_time'        => ["field" => "create_time", "operator" => ">"],
            'end_time'          => ["field" => "create_time", "operator" => "<"],
            'request_method'    => ["field" => "request_method", "operator" => "="],
            'equipment'         => ["field" => "equipment", "operator" => "="],
            'controller_action' => ["field" => "controller_action", "operator" => "="],
        ];

        $where_ands = [];

        if (IS_POST) {
            foreach ($fields as $param => $val) {
                if (isset($_POST[$param]) && !empty($_POST[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $get = $_POST[$param];
                    $_GET[$param] = $get;
                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        } else {
            foreach ($fields as $param => $val) {
                if (isset($_GET[$param]) && !empty($_GET[$param])) {
                    $operator = $val['operator'];
                    $field = $val['field'];
                    $get = $_GET[$param];
                    if ($operator == "like") {
                        $get = "%$get%";
                    }
                    array_push($where_ands, "$field $operator '$get'");
                }
            }
        }

        $where = join(" and ", $where_ands);
        $count = $this->request_record_model->where($where)->count();
        $page = $this->page($count, C("PAGE_NUMBER"));

        $result = $this->request_record_model
            ->limit($page->firstRow . ',' . $page->listRows)
            ->where($where)
            ->order('id desc')
            ->select();

        $tbodylist = '';
        foreach ($result as $k => $v) {
            $result[$k]['str_manage'] .= '<a class="js-ajax-delete" href="' . U('RequestRecord/delete', ['id' => $v['id']]) . '">删除</a>';
            $result[$k]['str_manage'] .= ' | ';
            $result[$k]['str_manage'] .= '<a href="javascript:open_iframe_dialog(\'' . U('RequestRecord/detail', ['id' => $v['id']]) . '\',\'详情\',\'\',\'90%\')">查看</a>';

            if ($v['result'])
                $result[$k]['success'] = 'class="text-success"';
            else
                $result[$k]['success'] = 'class="text-error"';

            $tbodylist .= '<tr>
            <td>' . ($k + 1) . '</td>
            <td>' . $v['request_method'] . '</td>
            <td>' . $v['controller_action'] . '</td>
            <td>' . ($this->arrayToString(json_decode($v['values'], true))) . '</td>
            <td ' . $result[$k]['success'] . '>' . $v['code'] . '</td>
            <td class="equipment">' . $v['equipment'] . '</td>
            <td>' . $v['create_time'] . '</td>
            <td>' . $result[$k]['str_manage'] . '</td>
        </tr>';
        }


        $this->assign('controller_action_option', $this->request_record_model->getControllerActionOption(I('controller_action')));
        $this->assign('request_method_option', $this->request_record_model->getRequestMethodOption(I('request_method')));
        $this->assign('equipment_option', $this->request_record_model->getEquipmentOption(I('equipment')));
        $this->assign('formget', I(''));
        $this->assign('tbodylist', $tbodylist);
        $this->assign("Page", $page->show());
    }

    public function detail($id)
    {
        if (empty($id)) $this->error('empty');
        $result = $this->request_record_model->find($id);
        if ($result) {
            $result['result'] = $result['result'] ? '成功' : '失败';
        }
        $data = json_decode($result['success_record'], true);
        $result['success_record'] = '';
        foreach ($data as $k => $v) {
            $result['success_record'] .= $k.': '.$v.'; ';
        }
        $this->assign('data', $result);
        $this->display();
    }

    private function arrayToString($array)
    {
        $str = '{';
        foreach ($array as $k => $v) {
            $str .= "'$k'='$v'";
            if (count($array) > $v) $str .= ',';
        }
        $str .= '}';
        return $str;
    }


    public function delete()
    {
        $id = I('id');
        if (empty($id)) $this->error('empty');
        $result = $this->request_record_model->delete($id);
        if ($result) $this->success('success');
        else $this->error('error');
    }


    public function truncate()
    {
        $this->request_record_model->where(['id' => ['neq', '-1']])->delete();
        $this->success('成功');
    }


    public function chartspage()
    {
        $data = $this->request_record_model
            ->group('controller_action')
            ->field('count(id) as count,controller_action')
            ->select();

        foreach ($data as $k => $v) {
            if (!strstr($v['controller_action'], "'")) {
                $dataName[] = $v['controller_action'];
                $dataGroup[] = $v['count'];
            }
        }

        $dataName = json_encode($dataName);
        $this->assign('dataName', $dataName);

        $dataGroup = json_encode($dataGroup);
        $this->assign('dataGroup', $dataGroup);

        S();

        $this->display();
    }


    public function equipment()
    {
        $data = $this->request_record_model
            ->field('equipment as name,count(id) as value')
            ->group('equipment')
            ->select();

        foreach ($data as $k => $v) {
            $dataName[] = $v['name'];
        }

        $dataList = json_encode($data);

        $this->assign('dataList', $dataList);

        $dataName = json_encode($dataName);

        $this->assign('dataName', $dataName);
        $this->display();
    }

    public function daycharts()
    {
        $data = $this->request_record_model
            ->field('count(id) as value,DATE_FORMAT(create_time , "%Y-%m-%d") as ctime')
            ->group('DATE_FORMAT(create_time , "%Y-%m-%d")')
            ->select();

        $data_ios = $this->request_record_model
            ->field('count(id) as value,DATE_FORMAT(create_time , "%Y-%m-%d") as ctime')
            ->group('DATE_FORMAT(create_time , "%Y-%m-%d")')
            ->where(['equipment' => 'IOS'])
            ->select();

        $data_android = $this->request_record_model
            ->field('count(id) as value,DATE_FORMAT(create_time , "%Y-%m-%d") as ctime')
            ->group('DATE_FORMAT(create_time , "%Y-%m-%d")')
            ->where(['equipment' => 'Android'])
            ->select();

        $data_other = $this->request_record_model
            ->field('count(id) as value,DATE_FORMAT(create_time , "%Y-%m-%d") as ctime')
            ->group('DATE_FORMAT(create_time , "%Y-%m-%d")')
            ->where(['equipment' => 'Other'])
            ->select();

        foreach ($data as $k => $v) {
            $dataName[] = date('m-d', strtotime($v['ctime']));

            $number = 0;
            foreach ($data_ios as $key => $value) {
                if ($value['ctime'] == $v['ctime']) {
                    $number = $value['value'];
                }
            }
            $dataListIos[] = $number;
            unset($value);
            $number = 0;

            foreach ($data_android as $key => $value) {
                if ($value['ctime'] == $v['ctime']) {
                    $number = $value['value'];
                }
            }
            $dataListAndroid[] = $number;
            unset($value);
            $number = 0;

            foreach ($data_other as $key => $value) {
                if ($value['ctime'] == $v['ctime']) {
                    $number = $value['value'];
                }
            }
            $dataListOther[] = $number;

            unset($value);
            $dataList[] = $v['value'];
        }


        $this->assign('dataListAndroid', json_encode($dataListAndroid));
        $this->assign('dataListIos', json_encode($dataListIos));
        $this->assign('dataListOther', json_encode($dataListOther));
        $this->assign('dataName', json_encode($dataName));

        $this->display();
    }


    public function shadow()
    {
        $data = $this->request_record_model
            ->field(
                'controller_action,count(id) as count,
                sum(case when code = 200 then 1 else 0 end) as c200,
                sum(case when code = 210 then 1 else 0 end) as c210,
                sum(case when code = 220 then 1 else 0 end) as c220,
                sum(case when code = 300 then 1 else 0 end) as c300,
                sum(case when code = 404 then 1 else 0 end) as c404,
                sum(case when result = 1 then 1 else 0 end) as success_count
                ')
            ->group('controller_action')
            ->select();

//        dump($this->request_record_model->getLastSql());

        $tableBody = '';
        foreach ($data as $k => $v) {
            $tableBody .= '<tr>
                        <td>' . $v['controller_action'] . '</td>
                        <td>' . $v['c200'] . '</td>
                        <td>' . $v['c210'] . '</td>
                        <td>' . $v['c220'] . '</td>
                        <td>' . $v['c300'] . '</td>
                        <td>' . $v['c404'] . '</td>
                        <td>' . ($v['count'] - $v['success_count']) . '</td>
                        <td>' . $v['count'] . '</td>
                        <td>' . number_format($v['success_count'] / $v['count'] * 100, 0) . '%</td>
                    </tr>';
        }


        $this->assign('tablebody', $tableBody);

        $this->display();
    }

}